package com.captain.leetcode2.链表;

import com.captain.leetcode.链表.ListNode;

import java.util.List;

/**
 * Des:
 * <p>
 * 给你一个链表的头节点 head 和一个特定值 x ，请你对链表进行分隔，使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
 * <p>
 * 你应当 保留 两个分区中每个节点的初始相对位置。
 * <p>
 * 输入：head = [1,4,3,2,5,2], x = 3
 * 输出：[1,2,2,4,3,5]
 * <p>
 * 输入：head = [2,1], x = 2
 * 输出：[1,2]
 *
 * @author XL
 * @Date 2021/9/1 10:46
 */
public class 分隔链表86 {

    public static void main(String[] args) {

        new 分隔链表86().partition2(ListNode.getInstance(), 3);

    }

    public ListNode partition(ListNode head, int x) {
        //分隔成两段, 第一次发现时 , 做切割成两段 , 如果再发现比x小的值, 前一段进行查询插入位置
        //[1,4,3,0,2,5,2]
        //[1,0,2,2,4,3,5]
        // * 输入：head = [1,4,3,2,5,2], x = 3
        // * 输出：[1,2,2,4,3,5]
        ListNode dummy = new ListNode(-101, head);
        ListNode cur = dummy;
        int big = 0;
        while (cur.next != null) {
            int val = cur.next.val;
            if (val >= x) {
                big++;
            }
            if (val < x && big > 0) {
                ListNode move = cur.next;
                int moveValue = move.val;
                ListNode preMove = dummy;
                cur.next = cur.next.next;
                while (preMove.next != null) {
                    int preMoveValue = preMove.next.val;
                    //如果小,则找到插入的位置
                    if (x <= preMoveValue) {
                        ListNode next = preMove.next;
                        preMove.next = move;
                        move.next = next;
                        break;
                    } else {
                        preMove = preMove.next;
                    }
                }
            } else {
                cur = cur.next;
            }
        }
        return dummy.next;
    }


    public ListNode partition2(ListNode head, int x) {
        if (head == null) return head;
        ListNode small = new ListNode(-1);
        ListNode smallCur = small;

        ListNode large = new ListNode(-1);
        ListNode largeCur = large;

        while (head != null) {
            int val = head.val;
            //小链表
            if (val < x) {
                smallCur.next = head;
                smallCur = smallCur.next;
            } else {
                largeCur.next = head;
                largeCur = largeCur.next;
            }
            head = head.next;
        }

        largeCur.next = null;
        smallCur.next = large.next;
        return small.next;
    }
}
